﻿/*
   　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System;
using System.Data;
using System.Text;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class Basic_Drug
    {
        public static BLL.Basic_Drug category = new BLL.Basic_Drug();
        public static Model.Basic_Drug model = new Model.Basic_Drug();

        public HttpContext Context;
        public string emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;
        

        public Basic_Drug()
        {
        }

        public Basic_Drug(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.id;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
            
        }

        public string save()
        {
            model.drugName = PageValidate.InputText(request["T_drug_name"], 50);
            model.Remarks = PageValidate.InputText(request["T_remarks"], 250);
            model.drugcycle = decimal.Parse( PageValidate.InputText(request["T_drugcycle"], 250));
            model.unit_id = PageValidate.InputText(request["T_unit_val"], 50);
            model.unit = PageValidate.InputText(request["T_unit"], 50);

            string id = PageValidate.InputText(request["id"], 50); 
            if (PageValidate.checkID(id))
            {
                model.IDCode = id;

                DataSet ds = category.GetList($" IDCode = '{id}' ");
                if (ds.Tables[0].Rows.Count == 0)
                    return XhdResult.Error("参数不正确，更新失败！").ToString();

                DataRow dr = ds.Tables[0].Rows[0];

           
                category.Update(model);

                string UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.drugName;
                string EventType = "药品周期修改";
                string EventID = model.IDCode;
                string Log_Content = null;

                if (dr["drugcycle"].ToString() != request["T_drugcycle"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "周期", dr["drugcycle"].ToString(), request["T_drugcycle"]);

               
                if (!string.IsNullOrEmpty(Log_Content))
                    Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);



            }

            else
            {
                
                model.IDCode = Guid.NewGuid().ToString();
                //model.create_id = emp_id;
                //model.create_time = DateTime.Now;
                category.Add(model);

            }
            return XhdResult.Success().ToString();
        }

        public string grid()
        {
            int PageIndex = int.Parse(request["page"] == null ? "1" : request["page"]);
            int PageSize = int.Parse(request["pagesize"] == null ? "30" : request["pagesize"]);
            string sortname = request["sortname"];
            string sortorder = request["sortorder"];

            if (string.IsNullOrEmpty(sortname))
                sortname = " IDCode";
            if (string.IsNullOrEmpty(sortorder))
                sortorder = "asc";

            string sorttext = " " + sortname + " " + sortorder;

            string Total;
            string serchtxt = $" 1=1 ";
            //if (!string.IsNullOrEmpty(request["categoryid"]))
            //    serchtxt += $" and category_id='{PageValidate.InputText(request["categoryid"], 50)}'";

            //if (!string.IsNullOrEmpty(request["stext"]))
            //    serchtxt += $" and product_name like N'%{ PageValidate.InputText(request["stext"], 255) }%'";

            //权限
            DataSet ds = category.GetList(PageSize, PageIndex, serchtxt, sorttext, out Total);

            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], Total);
            return (dt);

        }


        public string AllList()
        { 
            //权限
            DataSet ds = category.GetAllList();
            string dt = GetGridJSON.DataTableToJSON1(ds.Tables[0], "9999");
            return (dt);

        }

        public string tree()
        {
            DataSet ds = category.GetList($"1=1");
            var str = new StringBuilder();
            str.Append("[");
            str.Append(GetTreeString("root", ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string combo()
        {
            DataSet ds = category.GetList($"1=1");
            var str = new StringBuilder();
            str.Append("[");
            str.Append("{\"id\":\"root\",\"text\":\"无\",\"d_icon\":\"\"},");
            str.Append(GetTreeString("root", ds.Tables[0]));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        public string form(string id)
        {
            if (!PageValidate.checkID(id)) return "{}";
            id = PageValidate.InputText(id, 50);
            DataSet ds = category.GetList($" IDCode='{id}' ");
            return DataToJson.DataToJSON(ds);

        }

        //del
        public string del(string id)
        {
            if (!PageValidate.checkID(id)) return "false";
            id = PageValidate.InputText(id, 50);
          

            bool isdel = category.Delete(id);
            if (!isdel) return XhdResult.Error("系统错误！").ToString();

            //日志
            string EventType = "产品类别删除";

            string UserID = emp_id;
            string UserName = emp_name;
            string IPStreet = request.UserHostAddress;
            string EventID = id;
            string EventTitle = "";

            Syslog.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);

            return XhdResult.Success().ToString();

        }


        private static string GetTreeString(string Id, DataTable table)
        {
            DataRow[] rows = table.Select($"parentid='{Id}'");

            if (rows.Length == 0) return string.Empty;
            ;
            var str = new StringBuilder();

            foreach (DataRow row in rows)
            {
                str.Append("{\"id\":\"" + (string)row["id"] + "\",\"text\":\"" + (string)row["product_category"] + "\",\"d_icon\":\"../../" + (string)row["product_icon"] + "\"");

                if (GetTreeString((string)row["id"], table).Length > 0)
                {
                    str.Append(",\"children\":[");
                    str.Append(GetTreeString((string)row["id"], table));
                    str.Append("]},");
                }
                else
                {
                    str.Append("},");
                }
            }
            return str[str.Length - 1] == ',' ? str.ToString(0, str.Length - 1) : str.ToString();
        }
    }
}
